import Vue 			from 'vue'
import util 		from '../../util'
import axios 		from 'axios'
import { Toast,Dialog } 	from 'vant';
Vue.use(Toast,Dialog);

export default {
	name: 'buyType',
	data(){
		return {
			name:'',			//购买的币种名称
			account:0,			//购买币种数量
			amountOfMoney:0,	//购买金额
			userName:'',		//当前实名认证用户名
			OTCWorkTime:'',		//OTC服务时间
			list:[],
			loading:false,		//按钮是否加载中
			token:'',
			EOSAccount:'',
			ETHAccount:'',
			error:false
		}
	},
	computed:{
		isIphoneX(){
			return util.isIphoneX()
		},
		isIphone(){
			return util.client()
		},
		isMYKEY(){
			return util.isMYKEY()
		}
	},
	methods:{
		otcPayConfig(){
			//获取允许的支付方式
			return new Promise((resolve,reject) => {
				let params = {};
				if(this.isMYKEY) params.token = this.token || util.getToken();
				util.fetch(util.ajaxUrl()+`/mykey/otc-pay-config`,params).then(res => {
					if(res.retCode === 0){
						this.OTCWorkTime = res.retData.otc_serve_desc;
						util.setStorage('OTCWorkTime',this.OTCWorkTime)
						resolve(res.retData.recieve)
					}else{
						Toast(res.retMsg || '未知错误')
					}
					reject('')
				}).catch(error => {
					reject('')
					console.log(error)
				})
			})
		},
		payMethods(){
			//判断支付方式是否配置信息
			return new Promise((resolve,reject) => {
				util.fetch(util.ajaxUrl()+`/mykey/pay-methods`,{
					token:this.token || util.getToken()
				}).then(res => {
					if(res.retCode === 0){
						if(res.retData && res.retData.payMethods && Array.isArray(res.retData.payMethods)){
							resolve(res.retData.payMethods)
						}else{
							Toast('数据格式错误')
						}
					}else{
						Toast(res.retMsg || '未知错误')
					}
					reject('')
				}).catch(error => {
					reject('')
					console.log(error)
				})
			})
		},
		init(){
			//先渲染可能的缓存数据
			let mykeySell = util.getStorage('mykeySell');
			if(mykeySell) {
				this.list = JSON.parse(mykeySell);
				this.OTCWorkTime = util.getStorage('OTCWorkTime');
			};
			//拉取后台接口再渲染页面
			Promise.all([this.otcPayConfig(),this.payMethods()]).then(res => {
				util.bridgeData(res[0]).then(_list => {
					// _list为后端配置的支持的付款方式
					_list.map(item => {
						let _filter = res[1].filter(ele => ele.pay_type == item.type);
						item.onSet  = _filter.length > 0?1:2;		//1:已设置   2:未设置
						item.id     = _filter.length > 0?_filter[0].id:null;
					})
					//临时
					// _list[0].onSet = 2;
					// _list[1].onSet = 2;
					this.list = _list;
					util.setStorage('mykeySell',_list)
				})
			}).catch(error => {
				Toast('数据异常，请刷新重试')
			})
		},
		isOtcOutmoeny(){
			//判断是否有出售中的订单
			return new Promise(resolve => {
				util.fetch(util.ajaxUrl()+`/mykey/is-otc-outmoeny`,{
					token:this.token || util.getToken(),
				}).then(res => {
					if(res.retCode == 0){
						if(res.retData && res.retData.id){
							resolve(res.retData.id)
						}else{
							resolve('')
						}
					}else{
						resolve('')
						Toast(res.retMsg || '未知错误')
					}
				})
			})
		},
		makeOrder(){
			//下单
			let self = this;
			let accountId = '';
			let _filter = this.list.filter(item => item.isSelected && item.onSet==1);
			if(_filter.length == 0){
				Toast('请先设置收款方式')
				return
			}else{
				accountId = _filter[0].id;
			}
			this.loading = true;
			this.isOtcOutmoeny().then(orderId => {
				if(orderId){
					this.loading = false;
					//有出售中的订单，不能继续
					Dialog.confirm({
						title: '您有一笔出售订单未完成',
						message: '请先完成此订单交易',
						className:'sellType-dialog',
						cancelButtonColor:'#1989fa',
						confirmButtonText:'进入订单',
						cancelButtonText:'取消',
						overlayClass:'sellType-mark'
					}).then(() => {
						//获取订单状态
						util.fetch(util.ajaxUrl()+`/mykey/otc-outmoney-detail`,{
							token:self.token || util.getToken(),
							id:orderId
						}).then(res => {
							if(res.retCode == 0){
								if(res.retData.state && res.retData.state==-5){
									self.$router.replace({
										path:'/makeOrder',
										query:{
											orderId:orderId,
											isSell:1
										}
									})
								}else{
									self.$router.replace({
										path:'/orderDetail',
										query:{
											pageState:2,
											id:orderId
										}
									})
								}
							}else{
								Toast(res.retMsg || '未知错误')
							}
						})
					}).catch(() => {
						console.log('cancel')
					})
				}else{
					//正常出售
					util.checkDialog().then(confirm => {
						util.fetch(util.ajaxUrl()+`/mykey/otc-outmoney`,{
							token:this.token || util.getToken(),
							currency_id:this.name,		//币种
							number:this.account,		//数量
							account_id:accountId,		//收款ID
							address:this.ETHAccount,	//ETH账号
						}).then(res => {
							if(res.retCode == 0){
								this.$router.replace({
									path:'/makeOrder',
									query:{
										orderId:res.retData.id,
										isSell:1
									}
								})
							}else{
								this.loading = false;
								Toast(res.retMsg || '未知错误')
							}
						}).catch(error => {
							this.loading = false;
							console.log(error)
						})
					},cancel => {
						this.loading = false;
					})
				}
			})
		},
		goSet(_item){
			//点击设置
			if(_item && _item.onSet == 1) {
				//已设置支付方式，设置是否选中
				this.list.map(item => {
					item.isSelected = item.type === _item.type?true:false
				})
			}else if(_item && _item.onSet == 2){
				//未设置
				this.$router.push({
					path:'/setUserDropInfo',
					query:{
						type:_item.type
					}
				})
			}
		},
		goEdit(_item){
			//点击编辑
			if(_item && _item.onSet == 2){
				this.goSet(_item)
				return
			}
			this.$router.push({
				path:'/setUserDropInfo',
				query:{
					type:_item.type,
					edit:1
				}
			})
		},
		getPrice(){
			//获取每个B单价
			util.getPriceByName(this.name,2,this.account).then(price => {
				this.amountOfMoney = util.accMul(price,this.account).toFixed(2)
			}).catch(() => {
				Toast('获取实时单价失败')
			})
			setTimeout(() => {
				this.getPrice();
			},util.time)
		},
		goBack(){
			util.navigateBack(-1,this)
		}
	},
	created() {
		util.waitSDKReady().then(token => {
			this.token = token;
			this.EOSAccount = util.getStorage('EOSAccount');
			this.ETHAccount = util.getStorage('ETHAccount');
			let _query = this.$route.query;
			if(_query.name && _query.account){
				this.name = _query.name;
				this.account = _query.account;
				//检测没获取到EOSAccount或ETHAccount的情况
				if(this.isMYKEY && this.name === 'EOS' && !this.EOSAccount){
					Toast('获取EOS地址失败');
					this.error = true;
				}else if(this.isMYKEY && this.name != 'EOS' && (!this.ETHAccount || this.ETHAccount==='undefined')){
					Toast('获取ETH地址失败，请退出重试');
					this.error = true;
				}else{
					this.init();
					this.getPrice();
				}
			}else{
				Toast('数据格式错误')
			}
		}).catch((e) => {
			console.log(e)
			Toast('获取token失败')
		})
    }
}